"use client"

import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Progress } from "@/components/ui/progress"
import { useEffect, useMemo, useRef } from "react"
import * as echarts from "echarts"
import { LazyChart } from "./LazyLoader"
import {
  IconActivity,
  IconMap,
  IconUsers,
  IconRefresh,
  IconDownload,
  IconPlay,
  IconPause,
  IconTrendingUp,
  IconTrendingDown,
  IconChartBar,
  IconBed,
  IconAlertTriangle
} from "@tabler/icons-react"

// 基础 ECharts 容器
function EChartBase({ option, className }: { option: echarts.EChartsOption; className?: string }) {
  const ref = useRef<HTMLDivElement | null>(null)
  useEffect(() => {
    if (!ref.current) return
    const chart = echarts.init(ref.current)
    chart.setOption(option)

    // 监听窗口大小变化和全屏变化
    const onResize = () => {
      if (chart && !chart.isDisposed()) {
        chart.resize()
      }
    }

    // 监听全屏变化
    const onFullscreenChange = () => {
      setTimeout(() => {
        if (chart && !chart.isDisposed()) {
          chart.resize()
        }
      }, 100)
    }

    window.addEventListener('resize', onResize)
    document.addEventListener('fullscreenchange', onFullscreenChange)

    return () => {
      window.removeEventListener('resize', onResize)
      document.removeEventListener('fullscreenchange', onFullscreenChange)
      if (chart && !chart.isDisposed()) {
        chart.dispose()
      }
    }
  }, [option])

  return <div ref={ref} className={className || "w-full h-72"} />
}

// 热力图组件（ECharts）
const HeatmapChart = () => {
  const gridSizeX = 20
  const gridSizeY = 15
  const data = useMemo(() => {
    const d: [number, number, number][] = []
    for (let x = 0; x < gridSizeX; x++) {
      for (let y = 0; y < gridSizeY; y++) {
        d.push([x, y, Math.round(Math.random() * 100)])
      }
    }
    return d
  }, [])

  const option: echarts.EChartsOption = {
    grid: { left: 20, right: 10, top: 10, bottom: 25 },
    tooltip: { position: 'top' },
    xAxis: { type: 'category', data: Array.from({ length: gridSizeX }, (_, i) => i), splitArea: { show: true } },
    yAxis: { type: 'category', data: Array.from({ length: gridSizeY }, (_, i) => i), splitArea: { show: true } },
    visualMap: {
      min: 0,
      max: 100,
      calculable: true,
      orient: 'horizontal',
      left: 'center',
      bottom: 0
    },
    series: [
      {
        name: '密度',
        type: 'heatmap',
        data,
        emphasis: { itemStyle: { shadowBlur: 10, shadowColor: 'rgba(0,0,0,0.4)' } },
        progressive: 0
      }
    ]
  }

  return (
    <div className="chart-container w-full h-full">
      <EChartBase option={option} className="w-full h-full" />
    </div>
  )
}

// 趋势图表组件（ECharts）
const TrendChart = () => {
  const currentHour = new Date().getHours()
  const data = useMemo(
    () => Array.from({ length: 24 }, (_, i) => Math.max(0, 50 + Math.sin((i / 24) * Math.PI * 2) * 30 + (Math.random() - 0.5) * 20)),
    []
  )

  const option: echarts.EChartsOption = {
    grid: { left: 30, right: 10, top: 20, bottom: 25 },
    tooltip: { trigger: 'axis' },
    xAxis: { type: 'category', data: Array.from({ length: 24 }, (_, i) => `${i}:00`) },
    yAxis: { type: 'value' },
    series: [
      {
        type: 'bar',
        data,
        itemStyle: {
          color: (params: any) => (params.dataIndex === currentHour ? '#3b82f6' : '#a8b1c7')
        }
      }
    ],
    visualMap: [{ show: false, dimension: 0, pieces: [{ lte: currentHour - 1, color: '#a8b1c7' }, { gte: currentHour, color: '#3b82f6' }] }]
  }

  return (
    <div className="chart-container w-full h-full">
      <EChartBase option={option} className="w-full h-full" />
    </div>
  )
}

// 设备利用率图表
const UtilizationChart = () => {
  const departments = [
    { name: '急诊科', utilization: 85, trend: 'up', patients: 42 },
    { name: '内科', utilization: 72, trend: 'down', patients: 36 },
    { name: '外科', utilization: 91, trend: 'up', patients: 28 },
    { name: '儿科', utilization: 68, trend: 'stable', patients: 24 },
    { name: '妇产科', utilization: 55, trend: 'down', patients: 18 },
    { name: '心内科', utilization: 78, trend: 'up', patients: 32 }
  ]

  const getStatusColor = (utilization: number) => {
    if (utilization >= 80) return 'bg-red-100 border-red-200'
    if (utilization >= 60) return 'bg-yellow-100 border-yellow-200'
    return 'bg-green-100 border-green-200'
  }

  const getStatusDot = (utilization: number) => {
    if (utilization >= 80) return 'bg-red-500'
    if (utilization >= 60) return 'bg-yellow-500'
    return 'bg-green-500'
  }

  const getTrendIcon = (trend: string) => {
    switch (trend) {
      case 'up': return <IconTrendingUp className="w-4 h-4 text-green-600" />
      case 'down': return <IconTrendingDown className="w-4 h-4 text-red-600" />
      default: return <IconChartBar className="w-4 h-4 text-gray-600" />
    }
  }

  return (
    <div className="chart-container space-y-3 w-full h-full overflow-y-auto max-h-80">
      {departments.map((dept, index) => (
        <div key={index} className={`${getStatusColor(dept.utilization)} rounded-lg border p-4 transition-all hover:shadow-sm`}>
          <div className="flex items-center justify-between">
            <div className="flex items-center space-x-3">
              <div className={`w-3 h-3 rounded-full ${getStatusDot(dept.utilization)}`} />
              <div>
                <div className="text-gray-900 font-medium text-sm">{dept.name}</div>
                <div className="text-gray-600 text-xs">{dept.patients} 位患者</div>
              </div>
            </div>

            <div className="flex items-center space-x-4">
              <div className="text-right">
                <div className="text-gray-900 font-bold text-sm">{dept.utilization}%</div>
                <div className="text-gray-600 text-xs">使用率</div>
              </div>

              <div className="flex items-center space-x-2">
                {getTrendIcon(dept.trend)}
                <div className="w-16 h-2 bg-gray-200 rounded-full overflow-hidden">
                  <div
                    className={`h-full transition-all duration-500 ${
                      dept.utilization >= 80 ? 'bg-gradient-to-r from-red-500 to-red-400' :
                      dept.utilization >= 60 ? 'bg-gradient-to-r from-yellow-500 to-yellow-400' :
                        'bg-gradient-to-r from-green-500 to-green-400'
                      }`}
                    style={{ width: `${dept.utilization}%` }}
                  />
                </div>
              </div>
            </div>
          </div>
        </div>
      ))}
      
      {/* 统计摘要 */}
      <div className="mt-4 p-3 bg-gray-50 rounded-lg border">
        <div className="grid grid-cols-3 gap-4 text-center">
          <div>
            <div className="text-lg font-bold text-gray-900">{departments.filter(d => d.utilization >= 80).length}</div>
            <div className="text-xs text-gray-600">高负荷科室</div>
          </div>
          <div>
            <div className="text-lg font-bold text-gray-900">{Math.round(departments.reduce((sum, d) => sum + d.utilization, 0) / departments.length)}%</div>
            <div className="text-xs text-gray-600">平均使用率</div>
          </div>
          <div>
            <div className="text-lg font-bold text-gray-900">{departments.reduce((sum, d) => sum + d.patients, 0)}</div>
            <div className="text-xs text-gray-600">总患者数</div>
          </div>
        </div>
      </div>
    </div>
  )
}

// 病床使用率图表
const BedUtilizationChart = () => {
  const departments = [
    { name: '内科', total: 120, occupied: 108, trend: 'up' },
    { name: '外科', total: 85, occupied: 72, trend: 'down' },
    { name: '急诊', total: 45, occupied: 42, trend: 'up' },
    { name: 'ICU', total: 20, occupied: 18, trend: 'stable' },
    { name: '儿科', total: 60, occupied: 55, trend: 'up' }
  ]

  return (
    <div className="chart-container space-y-4">
      {departments.map((dept, index) => {
        const utilization = (dept.occupied / dept.total) * 100
        const getTrendIcon = (trend: string) => {
          switch (trend) {
            case 'up': return <IconTrendingUp className="w-4 h-4 text-green-500" />
            case 'down': return <IconTrendingDown className="w-4 h-4 text-red-500" />
            default: return <IconChartBar className="w-4 h-4 text-gray-500" />
          }
        }

        return (
          <div key={index} className="glass-card p-4 modern-shadow-hover">
            <div className="flex items-center justify-between mb-3">
              <div className="flex items-center space-x-2">
                <IconBed className="w-5 h-5 text-blue-600" />
                <span className="font-medium text-gray-900 dark:text-gray-100">{dept.name}</span>
              </div>
              {getTrendIcon(dept.trend)}
            </div>

            <div className="space-y-2">
              <div className="flex justify-between text-sm">
                <span className="text-gray-600 dark:text-gray-400">使用率</span>
                <span className="font-medium text-gray-900 dark:text-gray-100">{utilization.toFixed(1)}%</span>
              </div>

              <div className="w-full h-3 bg-gray-200 dark:bg-gray-700 rounded-full overflow-hidden">
                <div
                  className={`h-full transition-all duration-500 ${utilization > 90 ? 'bg-gradient-to-r from-red-500 to-red-400' :
                    utilization > 75 ? 'bg-gradient-to-r from-yellow-500 to-yellow-400' :
                      'bg-gradient-to-r from-green-500 to-green-400'
                    }`}
                  style={{ width: `${utilization}%` }}
                />
              </div>

              <div className="flex justify-between text-xs text-gray-500 dark:text-gray-400">
                <span>{dept.occupied}/{dept.total} 床位</span>
                <span>{dept.total - dept.occupied} 空闲</span>
              </div>
            </div>
          </div>
        )
      })}
    </div>
  )
}

// 预警统计图表
const AlertChart = () => {
  const alerts = [
    { type: '设备故障', count: 3, level: 'high', icon: IconAlertTriangle },
    { type: '人员密集', count: 8, level: 'medium', icon: IconUsers },
    { type: '温度异常', count: 2, level: 'low', icon: IconActivity },
    { type: '系统告警', count: 5, level: 'medium', icon: IconAlertTriangle }
  ]

  const getLevelColor = (level: string) => {
    switch (level) {
      case 'high': return 'text-red-600 bg-red-50 dark:bg-red-900/20'
      case 'medium': return 'text-yellow-600 bg-yellow-50 dark:bg-yellow-900/20'
      case 'low': return 'text-blue-600 bg-blue-50 dark:bg-blue-900/20'
      default: return 'text-gray-600 bg-gray-50 dark:bg-gray-900/20'
    }
  }

  return (
    <div className="chart-container">
      <div className="grid grid-cols-2 gap-4">
        {alerts.map((alert, index) => {
          const IconComponent = alert.icon
          return (
            <div key={index} className="glass-card p-4 modern-shadow-hover">
              <div className="flex items-center space-x-3">
                <div className={`p-2 rounded-lg ${getLevelColor(alert.level)}`}>
                  <IconComponent className="w-5 h-5" />
                </div>
                <div>
                  <div className="font-medium text-gray-900 dark:text-gray-100">{alert.type}</div>
                  <div className="text-2xl font-bold text-gray-900 dark:text-gray-100">{alert.count}</div>
                </div>
              </div>
            </div>
          )
        })}
      </div>
    </div>
  )
}

export {
  HeatmapChart,
  TrendChart,
  UtilizationChart,
  BedUtilizationChart,
  AlertChart
}
